import {
  wxRequest
} from '../../../utils/server.js';
import goods_share from "../../../component/painter/palette/goods";
const goodsShare = new goods_share()
const _wxRequest = new wxRequest();
const app = getApp()
Page({
  data: {
    imgUrl: app.globalData.imgUrl,
    uploadUrl: wx.getStorageSync('uploadUrl'),
    imageWidth: wx.getSystemInfoSync().windowWidth,
    adList: [],
    nvabarData: {
      showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示 
      // title: '商品详情', //导航栏 中间的标题
    },
    height: app.globalData.height * 2 + 20,
    goodsTabId: 1,
    num: 1,
    cardCur: 0,
    id: '',
    swiperList: [],
    goodsTabId: 1,
    show: false,
    mdc_show: false,
    arrt: false,
    assessList: [],
    defaultAddress: {},
    playIndex: '',
    detail: {},
    customermobile: ''
  },

  onLoad: function(option) {
    this.setData({
      id: option.id,
    })

  },
  onShow: function() {
    this.getDetail();
    if (wx.getStorageSync('Authorization')) {
      this.getGoodsAttend(); //关注商品
      this.getDefaultAddress()
    }
    this.getmobile()

  },

  //获取产品详情
  getDetail: function() {
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + '/gds/protected/goods/detail3?id=' + this.data.id,
      method: 'POST'
    }, (res) => {
      var detailVo = res.vo;
      var assessList = detailVo.assessList;
      assessList.map(item => {
        item.imgJson = JSON.parse(item.imgJson)
        //头像
        var avatar = item.avatar
        if (avatar && avatar.indexOf('https') != 0) {
          item.avatar = this.data.uploadUrl + item.avatar
        }
      })
      this.setData({
        detail: detailVo,
        adList: detailVo.coverImgs,
        assessList: assessList
      })
      this.findGoodsListByGroupId(); //推荐商品 
    })

  },

  //切换sku
  skuCheck: function(e) {
    var id = e.currentTarget.dataset.id
    this.setData({
      id
    })
    this.getDetail()
  },

  // tab切换
  checkTab(e) {
    var goodsTabId = e.currentTarget.dataset.id
    this.setData({
      goodsTabId: goodsTabId
    })
  },

  onClickButton: function() {
    Toast('点击按钮');
  },

  //弹窗选择sku选择
  showPopup: function() {
    this.setData({
      show: true
    });
  },

  //关闭弹窗
  onClose: function() {
    this.setData({
      show: false
    });
  },

  //更新数量 
  hadleNumChange: function(e) {
    this.setData({
      num: e.detail
    })
  },



  //推荐商品 
  findGoodsListByGroupId: function() {
    var url = '/gds/goods/recommend';

    if (this.data.detail.purchase == 1) {
      url = '/gds/goods/recommend2';
    }

    console.log(url, this.data.detail.purchase, 'this.data.detail.purchase')

    _wxRequest.wxAjax({
      url: app.globalData.apiUrl + url,
      method: 'post',
      data: {
        pageNo: 1,
        pageSize: 9,
        gdsId: this.data.id
      }
    }, (res) => {
      var list = res.list;
      var newarr = this.group(list, 3)
      this.setData({
        swiperList: newarr
      })
    })
  },

  group: function(array, subGroupLength) {
    let index = 0;
    let newArray = [];
    while (index < array.length) {
      newArray.push(array.slice(index, index += subGroupLength));
    }
    return newArray;
  },

  //更多商品
  toGoodsList: function() {
    wx.navigateTo({
      url: '/pages/good/list/index',
    })
  },

  //预览户型图
  imageList: function(e) {
    let current = this.data.uploadUrl + e.target.dataset.src;
    let urls = e.target.dataset.urls;
    if (urls && urls.length) {
      for (var i = 0; i < urls.length; i++) {
        urls[i] = this.data.uploadUrl + urls[i].imgPath
      };
    }
    wx.previewImage({
      current: current, // 当前显示图片的http链接
      urls: urls // 需要预览的图片http链接列表
    });
  },

  //分享 
  onShareAppMessage: function() {
    var image = this.data.uploadUrl + this.data.detail.coverImgs[0].imgPath;
    var uId = wx.getStorageSync('userInfo').id || ''
    return {
      title: this.data.detail.goodsName,
      imageUrl: image,
      path: '/pages/good/detail/index?id=' + this.data.id + '&empUserId=' + uId
    }
  },



  // 封面点击的时候相应的操作  获取视频在JS里的参数属性 
  //重点：点击图片接下来视频进行播放，但是视频播放后直接触发了视频的pause() 结局的方案是，延时150ms后再进行视频的播放，就完美解决了
  bindPlay: function(e) {
    var that = this;
    // that.videoContext = wx.createVideoContext('mdcVideo');
    // // that.videoContext.play()
    // that.videoContext.pause();
    // setTimeout(function () {
    //   that.videoContext.play()
    // }, 150);
    var id = e.currentTarget.dataset.index

    // 没有播放时播放视频
    if (!this.data.playIndex) {
      this.setData({
        playIndex: id
      })
      var videoContext = wx.createVideoContext(id) //这里对应的视频id
      videoContext.play()
    } else { // 有播放时先将prev暂停，再播放当前点击的current 
      var videoContextPrev = wx.createVideoContext(this.data.playIndex)
      if (this.data.playIndex != id) {
        videoContextPrev.pause()
      }
      this.setData({
        playIndex: id
      })
      var videoContextCurrent = wx.createVideoContext(id)
      videoContextCurrent.play()
    }
    that.setData({
      mdc_show: true
    })

  },


  outPlay: function() {
    this.setData({
      mdc_show: false
    })
  },



  //安卓系统能检测到 video touchemove 滑动的x距离，已此作为切换的swiper的凭证
  //ios系统，检测不到video touchemove 滑动的x距离，通过cover-view 点击事件进行切换
  mdc_move1: function(e) {
    var that = this;
    console.log(e)
    console.log(e.touches[0].pageX)
    var videoContextPrev = wx.createVideoContext('mdcVideo1');
    videoContextPrev.pause()

    if (e.touches[0].clientX > 20) {
      that.setData({
        mdc_show: false,
      })
    }
  },
  returnquanping: function(e) {
    var that = this;
    that.setData({
      mdc_show: false,
    })
  },

  //评价
  moreAssess: function(e) {
    var item = e.target.dataset.assessStatistics;
    var type = e.target.dataset.type || ''
    wx.navigateTo({
      url: '/pages/good/detail/assess?gdsId=' + this.data.id + '&type=' + type,
    })
  },


  //关注商品 
  customerAttend: function() {
    var that = this;
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + '/gds/protected/goodsAttend/addUserAttend?gdsId=' + this.data.id,
      method: 'post'
    }, (res) => {
      that.setData({
        arrt: true
      })
      wx.showToast({
        icon: 'none',
        title: '收藏成功'
      })
    })
  },

  //取消关注
  delCustomerAttend: function() {
    var that = this;
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + '/gds/protected/goodsAttend/deleteUserAttend?gdsId=' + this.data.id + '&gdsIdList=' + [this.data.id],
      method: 'post'
    }, (res) => {
      that.setData({
        arrt: false
      })
      wx.showToast({
        icon: 'none',
        title: '取消收藏'
      })
    })
  },


  // 查询商品关注
  getGoodsAttend: function() {
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + '/gds/protected/goodsAttend/existsUserAttend?gdsId=' + this.data.id,
      method: 'POST'
    }, (res) => {
      this.setData({
        arrt: res.flag
      })
    })
  },

  //获取默认地址
  getDefaultAddress: function() {
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + '/sys/protected/userAddress/defaultAddress',
      method: 'POST',
      data: {}
    }, (res) => {
      this.setData({
        defaultAddress: res.vo
      })
    })
  },


  //获取当前地址
  getLocation: function() {
    wx.getLocation({
      type: 'wgs84',
      success(res) {
        console.log(res)
      }
    })
  },


  //获取短码encodeShort
  decodeShort() {
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + '/sys/comm/encodeShort',
      method: 'POST',
      data: {
        longCode: 'id=' + this.data.id + '&empUserId=' + wx.getStorageSync('userInfo').id
      }

    }, (res) => {
      this.getCode(res.shortCode)
    })
  },


  //获取二维吗
  getCode(scene) {
    var that = this
    _wxRequest.wxAjax({
      url: app.globalData.apiUrl + '/odr/mall/getWxaCodeUnlimit',
      contentType: "application/x-www-form-urlencoded",
      method: 'POST',
      data: {
        page: '/pages/good/detail/index',
        width: 750,
        scene
      }
    }, (res) => {
      console.log(res, 'getCode')
      that.setData({
        qrCode: res.url
      }, () => {
        that.toShare()
      })
    })
  },


  //分享
  toShare() {
    var qrCode = this.data.qrCode
    this.setData({
      shareImgTemplate: goodsShare.palette(qrCode, this.data.detail, 0)
    });
    wx.showLoading({
      title: "努力生成中..."
    });
  },

  //图片生成完成后呈现在页面上
  onShareImgOK(e) {
    this.setData({
      shareImgUrl: e.detail.path
    });
    wx.hideLoading();
    this.previewShareImg();
  },
  previewShareImg(e) {
    let url = this.data.shareImgUrl;
    wx.previewImage({
      current: url,
      urls: [url]
    });
  },

  //获取电话号码
  getmobile() {
    _wxRequest.wxAjax({
        url: app.globalData.apiUrl + '/org/bizOrg/getServicePhone',
        method: 'get',
      }, (res) => {
        wx.setStorageSync('customermobile', res.data)
        this.setData({
          customermobile: res.data
        })
      })
  },

  makePhoneCall(e) {
    let phone = e.currentTarget.dataset.contacttel;
    console.log(phone)
    if (phone) {
      wx.makePhoneCall({
        phoneNumber: phone
      });
    }
  }




})